package com.cool4j.generator.db

import com.cool4j.generator.entity.Column
import com.cool4j.generator.entity.Table
import com.cool4j.generator.exception.ExceptionMessage
import com.cool4j.generator.exception.GeneratorException
import org.apache.commons.lang3.StringUtils

import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException

/**
 * MySQL 数据库连接器
 *
 * @author Frank create on 16/1/7 14:56
 */
class MySqlConnection implements DatabaseConnection {

    @Override
    Connection getConnection(String user, String password, String driver, String url) throws Exception {
        Connection conn = null
        Class.forName(driver).newInstance()
        conn = DriverManager.getConnection(url, user, password)
        return conn
    }

    @Override
    List<Column> getColumnList(conn, tableName, user) throws Exception {
        def columnList = []
        def databaseMetaData
        def resultSet
        def primarySet

        try {
            databaseMetaData = conn.getMetaData()
            resultSet = databaseMetaData.getColumns(null, user, tableName, "%")
            primarySet = databaseMetaData.getPrimaryKeys(null, null, tableName)
            while (resultSet.next()) {
                def column = new Column()
                /* 因为创建数据库表时,字段名不可能为空,所以可以不用判断是否为空 */
                column.setColumnName(resultSet.getString("COLUMN_NAME"))
                def primaryKeyName = primarySet.getString("COLUMN_NAME")
                StringUtils.equals(column.getColumnName(), primaryKeyName) ? column.setIsPrimary(true) : column.setIsPrimary(false)
                column.setColumnSize(resultSet.getString("COLUMN_SIZE"))
                column.setRemark(resultSet.getString("REMARKS"))
                column.setTypeName(resultSet.getString("TYPE_NAME"))
                column.setIsNullable(resultSet.getString("IS_NULLABLE"))

                columnList.add(column)
            }
        } catch (SQLException e) {
            throw new GeneratorException(ExceptionMessage.EXCEPTION_SQL_EXECUTE, e)
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close()
                    resultSet = null
                }
            } catch (SQLException e) {
                throw new GeneratorException(ExceptionMessage.EXCEPTION_CLOSE_CONNECTION, e)
            }
        }

        return columnList
    }

    @Override
    Table getTable(conn, tableName) throws Exception {
        def table = new Table()
        def stmt
        def resultSet

        try {
            stmt = conn.createStatement()
            resultSet = stmt.executeQuery("SHOW CREATE TABLE " + tableName)
            if (resultSet.next()) {
                def newTableName = resultSet.getString(1)
                if (StringUtils.equals(tableName, newTableName)) {
                    table.setTableName(newTableName)
                    table.setRemark(parseComment(resultSet.getString(2)))
                } else {
                    throw new GeneratorException(ExceptionMessage.EXCEPTION_TABLE + tableName + ExceptionMessage.EXCEPTION_NOT_FOUND)
                }
            }
        } catch (SQLException e) {
            throw new GeneratorException(ExceptionMessage.EXCEPTION_SQL_EXECUTE, e)
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close()
                    resultSet = null
                }
                if (stmt != null) {
                    stmt.close()
                    stmt = null
                }
            } catch (SQLException e) {
                throw new GeneratorException(ExceptionMessage.EXCEPTION_CLOSE_CONNECTION, e)
            }
        }

        return table
    }

    private String parseComment(str) {
        def comment = ""
        def index = str.indexOf("COMMENT='")
        if (index < 0) return ""
        comment = str.substring(index + 9)
        comment = comment.substring(0, comment.length() - 1)  // 去掉末尾的 ' 号
        return comment
    }

}
